#pragma once
#include<iostream>
#include<pthread.h>

namespace LockModule
{

	// 互斥锁一般不允许拷贝，不允许赋值，保证进程中使用的是同一把锁
	class Mutex
	{
	public:
		Mutex(const Mutex&) = delete;
		const Mutex& operator = (const Mutex&) = delete;


		Mutex()
		{
			int n = ::pthread_mutex_init(&_lock,nullptr); //成功为0，失败返回错误码
			(void)n;
		}
		~Mutex()
		{
			int n = ::pthread_mutex_destroy(&_lock);
			(void)n;
		}
		void Lock()
		{
			int n = ::pthread_mutex_lock(&_lock);
			(void)n;
		}

		pthread_mutex_t* LockPtr()
		{
			return &_lock;
		}
		
		void Unlock()
		{
			int n = ::pthread_mutex_unlock(&_lock);
			(void)n;
		}

	private:
		pthread_mutex_t _lock;
	};



	class LockGuard  //锁保护装置
	{
	public:
		LockGuard(Mutex &mtx):_mtx(mtx)
		{
			_mtx.Lock();
		}
		~LockGuard()
		{
			_mtx.Unlock();
		}

	private:
		Mutex &_mtx;
	};
};